import { defineStore } from 'pinia';
import { computed, reactive } from 'vue';
import { RouteRecordName, RouteRecordRaw } from 'vue-router';
import { RouteUrlEnum } from '@/config/router_config/router_components';
export interface MenuItem{
  label: string;
  routeName: RouteRecordName | undefined;
  routeUrl: string;
  icon: string;
  hidden: boolean,
  children?: MenuItem[];
}

export class MenuState {
  private _menuList: MenuItem[];
  private _nowActiveMenu: RouteUrlEnum;
  public constructor () {
    this._menuList = [];
    this._nowActiveMenu = RouteUrlEnum.homePage;
  }

  get nowActiveMenu (): RouteUrlEnum {
    return this._nowActiveMenu;
  }

  set nowActiveMenu (value: RouteUrlEnum) {
    this._nowActiveMenu = value;
  }

  get menuList (): MenuItem[] {
    return this._menuList;
  }

  set menuList (value: MenuItem[]) {
    this._menuList = value;
  }
}
// 将路由转换成菜单
const transferRoutesToMenu = (originRoutes: Array<RouteRecordRaw>): MenuItem[] => {
  const originMenuItems: MenuItem[] = [];
  for (const item of originRoutes) {
    const hidden: boolean = item.meta ? <boolean>item.meta.hidden : false;
    if (!hidden) {
      const label: string = item.meta ? <string>item.meta.title : '未命名菜单';
      const routeName: RouteRecordName | undefined = item.name;
      const routeUrl: string = item.path;
      const icon: string = '';
      const menuItem: MenuItem = { label, routeName, routeUrl, hidden, icon };
      if (item.children) {
        menuItem.children = transferRoutesToMenu(item.children);
      }
      originMenuItems.push(menuItem);
    }
  }
  return originMenuItems;
};

export const useMenuStore = defineStore('menu', () => {
  // 菜单状态对象
  const menuState = reactive<MenuState>(new MenuState());
  // 所有得getters
  const menuList = computed((): MenuItem[] => menuState.menuList);
  const nowActiveMenu = computed((): RouteUrlEnum => menuState.nowActiveMenu);
  // 所有得actions
  const createMenuListFromRoutes = (routes: RouteRecordRaw[]) => {
    menuState.menuList = transferRoutesToMenu(routes);
  };
  // 改变当前激活的菜单
  const changeActiveMenu = (menuIndex: RouteUrlEnum) => {
    menuState.nowActiveMenu = menuIndex;
  };
  return {
    menuState, menuList, nowActiveMenu, createMenuListFromRoutes, changeActiveMenu
  };
});
